<template>
    <el-dialog v-model="visible" :title="dialogTitle" width="700px" :close-on-click-modal="false" @close="handleClose">
        <el-form :model="formData" ref="formRef" :rules="formRules" label-width="120px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="域名：" prop="domain">
                        <el-input v-model="formData.domain" placeholder="请输入域名" class="form-input" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="账户：" prop="accountId">
                        <el-select v-model="formData.accountId" placeholder="请选择账户名称" clearable>
                            <el-option v-for="item in accountNameOptions" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="隐私协议：" prop="privacyPolicy">
                        <el-select v-model="formData.privacyPolicy" placeholder="请选择隐私协议" class="form-input" clearable
                            filterable>
                            <el-option v-for="item in privacyPolicyOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="用户手册：" prop="userManual">
                        <el-select v-model="formData.userManual" placeholder="请选择用户手册" class="form-input" clearable
                            filterable>
                            <el-option v-for="item in userManualOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="Imprint：" prop="Imprint">
                        <el-select v-model="formData.Imprint" placeholder="请选择Imprint" class="form-input" clearable
                            filterable>
                            <el-option v-for="item in imprintOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系方式：" prop="contact">
                        <el-select v-model="formData.contact" placeholder="请选择联系方式" class="form-input" clearable
                            filterable>
                            <el-option v-for="item in contactOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="UI模板：" prop="uiTemplate">
                        <el-select v-model="formData.uiTemplate" placeholder="请选择UI模板" class="form-input" clearable
                            filterable>
                            <el-option v-for="item in uiTemplateOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="投流网站：" prop="isRsoc">
                        <el-radio-group v-model="formData.isRsoc">
                            <el-radio value="1" style="margin-right: 10px;">是</el-radio>
                            <el-radio value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="网站标签：" prop="tagList">
                <el-select v-model="formData.tagList" placeholder="请选择网站标签" class="form-input" multiple>
                    <el-option v-for="item in tagListOptions" :key="item.id" :label="item.tagNameEn" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="category：" prop="category">
                <el-cascader style="width: 100%;" clearable v-model="formData.category" :options="categoryOptions"
                    filterable multiple :props="categoryProps" placeholder="请选择文章分类" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    {{ isEditMode ? '修改' : '新增' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import service from '../../config/index';


interface ConfigFormData {
    id?: string
    domain: string
    privacyPolicy: string
    userManual: string
    Imprint: string
    contact: string
    uiTemplate: string
    isRsoc: string
    accountId: number | null
    tagList: string[]
    category: any[]
}

interface Props {
    modelValue: boolean
    isEditMode?: boolean
    editData?: ConfigFormData | null
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    isEditMode: false,
    editData: null
})

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    submit: [data: ConfigFormData]
    cancel: []
}>()

const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
    return props.isEditMode ? '修改运营配置' : '新增运营配置'
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const formData = ref<ConfigFormData>({
    id: '',
    domain: '',
    privacyPolicy: '',
    userManual: '',
    Imprint: '',
    contact: '',
    uiTemplate: '',
    isRsoc: '0',
    accountId: null,
    tagList: [],
    category: []
})

// 级联选择器配置
const categoryProps = {
    checkStrictly: true,
    multiple: true,
}

// 选项列表
const privacyPolicyOptions = ref([
    { label: '隐私协议1', value: 'privacy1' },
    { label: '隐私协议2', value: 'privacy2' },
    { label: '隐私协议3', value: 'privacy3' }
])

const userManualOptions = ref([
    { label: '用户手册1', value: 'manual1' },
    { label: '用户手册2', value: 'manual2' },
    { label: '用户手册3', value: 'manual3' }
])

const imprintOptions = ref([
    { label: 'Imprint1', value: 'imprint1' },
    { label: 'Imprint2', value: 'imprint2' },
    { label: 'Imprint3', value: 'imprint3' }
])

const contactOptions = ref([
    { label: '联系方式1', value: 'contact1' },
    { label: '联系方式2', value: 'contact2' },
    { label: '联系方式3', value: 'contact3' }
])

const uiTemplateOptions = ref([
    { label: '模板1', value: 'template1' },
    { label: '模板2', value: 'template2' },
    { label: '模板3', value: 'template3' }
])

const tagListOptions = ref([])
const getTagAll = () => {
    service.get('/tag/getAll')
        .then(response => {
            tagListOptions.value = response.data
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

//账户
const accountNameOptions = ref([])
const getAccount = () => {
    service.get('/account/getAll')
        .then(response => {
            accountNameOptions.value = response?.data
            accountNameOptions.value.push({ id: -1, name: '其他' })
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

// 分类选项
const categoryOptions = ref<any[]>([])
const buildTree = (nodes: any[], parentId: any = null): any[] => {
    return nodes
        .filter(node => node.parentId === parentId)
        .map(node => {
            const children = buildTree(nodes, node.value);
            return {
                ...node,
                ...(children.length > 0 ? { children } : {})
            };
        });
}
const getArticleCategory = () => {
    service.get('/article/allCategory')
        .then(response => {
            const treeData = response.data?.map((item: any) => ({
                label: item.name,
                value: item.id,
                parentId: item.parentId,
                alias: item.alias
            }));
            categoryOptions.value = buildTree(treeData);
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}


// 表单验证规则
const formRules = reactive<FormRules>({
    domain: [
        { required: true, message: '请输入域名', trigger: 'blur' },
        {
            pattern: /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,
            message: '请输入正确的域名格式',
            trigger: 'blur'
        }
    ],
    privacyPolicy: [
        { required: true, message: '请选择隐私协议', trigger: 'change' }
    ],
    userManual: [
        { required: true, message: '请选择用户手册', trigger: 'change' }
    ],
    Imprint: [
        { required: true, message: '请选择Imprint', trigger: 'change' }
    ],
    contact: [
        { required: true, message: '请选择联系方式', trigger: 'change' }
    ],
    uiTemplate: [
        { required: true, message: '请选择UI模板', trigger: 'change' }
    ],
    isRsoc: [
        { required: true, message: '请选择是否是投流网站', trigger: 'change' }
    ],
    accountId: [
        { required: true, message: '请选择账户名称', trigger: 'change' }
    ],
    tagList: [
        { required: true, message: '请选择网站标签', trigger: 'change', type: 'array' }
    ],
    category: [
        { required: true, message: '请选择文章分类', trigger: 'change', type: 'array' }
    ]
})

// 监听编辑数据变化
watch(() => props.editData, (newData) => {
    if (newData) {
        formData.value = {
            id: newData.id || '',
            domain: newData.domain || '',
            privacyPolicy: newData.privacyPolicy || '',
            userManual: newData.userManual || '',
            Imprint: newData.Imprint || '',
            contact: newData.contact || '',
            uiTemplate: newData.uiTemplate || '',
            isRsoc: newData.isRsoc || '0',
            accountId: newData.accountId || null,
            tagList: newData.tagList || [],
            category: newData.category || []
        }
    }
}, { immediate: true, deep: true })

// 监听对话框打开状态，重置表单
watch(() => props.modelValue, (newVal) => {
    if (newVal && !props.isEditMode) {
        resetForm()
    }
})

// 重置表单
const resetForm = () => {
    formData.value = {
        id: '',
        domain: '',
        privacyPolicy: '',
        userManual: '',
        Imprint: '',
        contact: '',
        uiTemplate: '',
        isRsoc: '0',
        accountId: null,
        tagList: [],
        category: []
    }
    formRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                emit('submit', { ...formData.value })
            } catch (error: any) {
                ElMessage.error(error?.message || '操作失败')
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 取消
const handleCancel = () => {
    emit('cancel')
    visible.value = false
}

// 关闭对话框
const handleClose = () => {
    resetForm()
}

// 暴露方法给父组件
defineExpose({
    resetForm
})

// 组件挂载时获取数据
onMounted(async () => {
    await getAccount()
    await getTagAll()
    await getArticleCategory()
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 600;
}

:deep(.el-form-item) {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>
